package com.funsport.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 天气服务 - 高德天气API（带缓存）
 */
@Slf4j
@Service
public class WeatherService {
    
    @Value("${weather.api.key:}")
    private String apiKey;
    
    @Value("${weather.api.url:https://restapi.amap.com}")
    private String apiUrl;
    
    @Value("${weather.api.cache-minutes:30}")
    private int cacheMinutes;
    
    private final RestTemplate restTemplate = new RestTemplate();
    
    /**
     * 天气缓存（城市 -> 缓存数据）
     */
    private final Map<String, WeatherCache> weatherCacheMap = new ConcurrentHashMap<>();
    
    /**
     * 天气预报缓存（城市_天数 -> 缓存数据）
     */
    private final Map<String, WeatherCache> forecastCacheMap = new ConcurrentHashMap<>();
    
    /**
     * 缓存数据结构
     */
    private static class WeatherCache {
        private final Map<String, Object> data;
        private final LocalDateTime cacheTime;
        
        public WeatherCache(Map<String, Object> data) {
            this.data = data;
            this.cacheTime = LocalDateTime.now();
        }
        
        public Map<String, Object> getData() {
            return data;
        }
        
        public boolean isExpired(int minutes) {
            return LocalDateTime.now().isAfter(cacheTime.plusMinutes(minutes));
        }
        
        public LocalDateTime getCacheTime() {
            return cacheTime;
        }
    }
    
    /**
     * 城市名称到城市编码映射（高德天气使用adcode）
     * 说明：高德天气API要求使用城市adcode，格式为6位行政区划代码
     */
    private static final Map<String, String> CITY_CODE_MAP = new HashMap<>();
    
    static {
        // 直辖市（4个）
        CITY_CODE_MAP.put("北京", "110000");
        CITY_CODE_MAP.put("北京市", "110000");
        CITY_CODE_MAP.put("上海", "310000");
        CITY_CODE_MAP.put("上海市", "310000");
        CITY_CODE_MAP.put("天津", "120000");
        CITY_CODE_MAP.put("天津市", "120000");
        CITY_CODE_MAP.put("重庆", "500000");
        CITY_CODE_MAP.put("重庆市", "500000");
        
        // 广东省（21个地级市）
        CITY_CODE_MAP.put("广州", "440100");
        CITY_CODE_MAP.put("广州市", "440100");
        CITY_CODE_MAP.put("深圳", "440300");
        CITY_CODE_MAP.put("深圳市", "440300");
        CITY_CODE_MAP.put("珠海", "440400");
        CITY_CODE_MAP.put("汕头", "440500");
        CITY_CODE_MAP.put("佛山", "440600");
        CITY_CODE_MAP.put("韶关", "440200");
        CITY_CODE_MAP.put("湛江", "440800");
        CITY_CODE_MAP.put("肇庆", "441200");
        CITY_CODE_MAP.put("江门", "440700");
        CITY_CODE_MAP.put("茂名", "440900");
        CITY_CODE_MAP.put("惠州", "441300");
        CITY_CODE_MAP.put("梅州", "441400");
        CITY_CODE_MAP.put("汕尾", "441500");
        CITY_CODE_MAP.put("河源", "441600");
        CITY_CODE_MAP.put("阳江", "441700");
        CITY_CODE_MAP.put("清远", "441800");
        CITY_CODE_MAP.put("东莞", "441900");
        CITY_CODE_MAP.put("中山", "442000");
        CITY_CODE_MAP.put("潮州", "445100");
        CITY_CODE_MAP.put("揭阳", "445200");
        CITY_CODE_MAP.put("云浮", "445300");
        
        // 浙江省（11个地级市）
        CITY_CODE_MAP.put("杭州", "330100");
        CITY_CODE_MAP.put("杭州市", "330100");
        CITY_CODE_MAP.put("宁波", "330200");
        CITY_CODE_MAP.put("温州", "330300");
        CITY_CODE_MAP.put("嘉兴", "330400");
        CITY_CODE_MAP.put("湖州", "330500");
        CITY_CODE_MAP.put("绍兴", "330600");
        CITY_CODE_MAP.put("金华", "330700");
        CITY_CODE_MAP.put("衢州", "330800");
        CITY_CODE_MAP.put("舟山", "330900");
        CITY_CODE_MAP.put("台州", "331000");
        CITY_CODE_MAP.put("丽水", "331100");
        
        // 江苏省（13个地级市）
        CITY_CODE_MAP.put("南京", "320100");
        CITY_CODE_MAP.put("南京市", "320100");
        CITY_CODE_MAP.put("无锡", "320200");
        CITY_CODE_MAP.put("徐州", "320300");
        CITY_CODE_MAP.put("常州", "320400");
        CITY_CODE_MAP.put("苏州", "320500");
        CITY_CODE_MAP.put("苏州市", "320500");
        CITY_CODE_MAP.put("南通", "320600");
        CITY_CODE_MAP.put("连云港", "320700");
        CITY_CODE_MAP.put("淮安", "320800");
        CITY_CODE_MAP.put("盐城", "320900");
        CITY_CODE_MAP.put("扬州", "321000");
        CITY_CODE_MAP.put("镇江", "321100");
        CITY_CODE_MAP.put("泰州", "321200");
        CITY_CODE_MAP.put("宿迁", "321300");
        
        // 四川省（21个地级市）
        CITY_CODE_MAP.put("成都", "510100");
        CITY_CODE_MAP.put("成都市", "510100");
        CITY_CODE_MAP.put("自贡", "510300");
        CITY_CODE_MAP.put("攀枝花", "510400");
        CITY_CODE_MAP.put("泸州", "510500");
        CITY_CODE_MAP.put("德阳", "510600");
        CITY_CODE_MAP.put("绵阳", "510700");
        CITY_CODE_MAP.put("广元", "510800");
        CITY_CODE_MAP.put("遂宁", "510900");
        CITY_CODE_MAP.put("内江", "511000");
        CITY_CODE_MAP.put("乐山", "511100");
        CITY_CODE_MAP.put("南充", "511300");
        CITY_CODE_MAP.put("眉山", "511400");
        CITY_CODE_MAP.put("宜宾", "511500");
        CITY_CODE_MAP.put("广安", "511600");
        CITY_CODE_MAP.put("达州", "511700");
        CITY_CODE_MAP.put("雅安", "511800");
        CITY_CODE_MAP.put("巴中", "511900");
        CITY_CODE_MAP.put("资阳", "512000");
        
        // 湖北省（13个地级市）
        CITY_CODE_MAP.put("武汉", "420100");
        CITY_CODE_MAP.put("武汉市", "420100");
        CITY_CODE_MAP.put("黄石", "420200");
        CITY_CODE_MAP.put("十堰", "420300");
        CITY_CODE_MAP.put("宜昌", "420500");
        CITY_CODE_MAP.put("襄阳", "420600");
        CITY_CODE_MAP.put("鄂州", "420700");
        CITY_CODE_MAP.put("荆门", "420800");
        CITY_CODE_MAP.put("孝感", "420900");
        CITY_CODE_MAP.put("荆州", "421000");
        CITY_CODE_MAP.put("黄冈", "421100");
        CITY_CODE_MAP.put("咸宁", "421200");
        CITY_CODE_MAP.put("随州", "421300");
        
        // 湖南省（14个地级市）
        CITY_CODE_MAP.put("长沙", "430100");
        CITY_CODE_MAP.put("长沙市", "430100");
        CITY_CODE_MAP.put("株洲", "430200");
        CITY_CODE_MAP.put("湘潭", "430300");
        CITY_CODE_MAP.put("衡阳", "430400");
        CITY_CODE_MAP.put("邵阳", "430500");
        CITY_CODE_MAP.put("岳阳", "430600");
        CITY_CODE_MAP.put("常德", "430700");
        CITY_CODE_MAP.put("张家界", "430800");
        CITY_CODE_MAP.put("益阳", "430900");
        CITY_CODE_MAP.put("郴州", "431000");
        CITY_CODE_MAP.put("永州", "431100");
        CITY_CODE_MAP.put("怀化", "431200");
        CITY_CODE_MAP.put("娄底", "431300");
        
        // 河南省（17个地级市）
        CITY_CODE_MAP.put("郑州", "410100");
        CITY_CODE_MAP.put("郑州市", "410100");
        CITY_CODE_MAP.put("开封", "410200");
        CITY_CODE_MAP.put("洛阳", "410300");
        CITY_CODE_MAP.put("平顶山", "410400");
        CITY_CODE_MAP.put("安阳", "410500");
        CITY_CODE_MAP.put("鹤壁", "410600");
        CITY_CODE_MAP.put("新乡", "410700");
        CITY_CODE_MAP.put("焦作", "410800");
        CITY_CODE_MAP.put("濮阳", "410900");
        CITY_CODE_MAP.put("许昌", "411000");
        CITY_CODE_MAP.put("漯河", "411100");
        CITY_CODE_MAP.put("三门峡", "411200");
        CITY_CODE_MAP.put("南阳", "411300");
        CITY_CODE_MAP.put("商丘", "411400");
        CITY_CODE_MAP.put("信阳", "411500");
        CITY_CODE_MAP.put("周口", "411600");
        
        // 山东省（16个地级市）
        CITY_CODE_MAP.put("济南", "370100");
        CITY_CODE_MAP.put("济南市", "370100");
        CITY_CODE_MAP.put("青岛", "370200");
        CITY_CODE_MAP.put("青岛市", "370200");
        CITY_CODE_MAP.put("淄博", "370300");
        CITY_CODE_MAP.put("枣庄", "370400");
        CITY_CODE_MAP.put("东营", "370500");
        CITY_CODE_MAP.put("烟台", "370600");
        CITY_CODE_MAP.put("潍坊", "370700");
        CITY_CODE_MAP.put("济宁", "370800");
        CITY_CODE_MAP.put("泰安", "370900");
        CITY_CODE_MAP.put("威海", "371000");
        CITY_CODE_MAP.put("日照", "371100");
        CITY_CODE_MAP.put("临沂", "371300");
        CITY_CODE_MAP.put("德州", "371400");
        CITY_CODE_MAP.put("聊城", "371500");
        CITY_CODE_MAP.put("滨州", "371600");
        CITY_CODE_MAP.put("菏泽", "371700");
        
        // 福建省（9个地级市）
        CITY_CODE_MAP.put("福州", "350100");
        CITY_CODE_MAP.put("福州市", "350100");
        CITY_CODE_MAP.put("厦门", "350200");
        CITY_CODE_MAP.put("厦门市", "350200");
        CITY_CODE_MAP.put("莆田", "350300");
        CITY_CODE_MAP.put("三明", "350400");
        CITY_CODE_MAP.put("泉州", "350500");
        CITY_CODE_MAP.put("漳州", "350600");
        CITY_CODE_MAP.put("南平", "350700");
        CITY_CODE_MAP.put("龙岩", "350800");
        CITY_CODE_MAP.put("宁德", "350900");
        
        // 陕西省（10个地级市）
        CITY_CODE_MAP.put("西安", "610100");
        CITY_CODE_MAP.put("西安市", "610100");
        CITY_CODE_MAP.put("铜川", "610200");
        CITY_CODE_MAP.put("宝鸡", "610300");
        CITY_CODE_MAP.put("咸阳", "610400");
        CITY_CODE_MAP.put("渭南", "610500");
        CITY_CODE_MAP.put("延安", "610600");
        CITY_CODE_MAP.put("汉中", "610700");
        CITY_CODE_MAP.put("榆林", "610800");
        CITY_CODE_MAP.put("安康", "610900");
        CITY_CODE_MAP.put("商洛", "611000");
        
        // 辽宁省（14个地级市）
        CITY_CODE_MAP.put("沈阳", "210100");
        CITY_CODE_MAP.put("沈阳市", "210100");
        CITY_CODE_MAP.put("大连", "210200");
        CITY_CODE_MAP.put("大连市", "210200");
        CITY_CODE_MAP.put("鞍山", "210300");
        CITY_CODE_MAP.put("抚顺", "210400");
        CITY_CODE_MAP.put("本溪", "210500");
        CITY_CODE_MAP.put("丹东", "210600");
        CITY_CODE_MAP.put("锦州", "210700");
        CITY_CODE_MAP.put("营口", "210800");
        CITY_CODE_MAP.put("阜新", "210900");
        CITY_CODE_MAP.put("辽阳", "211000");
        CITY_CODE_MAP.put("盘锦", "211100");
        CITY_CODE_MAP.put("铁岭", "211200");
        CITY_CODE_MAP.put("朝阳", "211300");
        CITY_CODE_MAP.put("葫芦岛", "211400");
        
        // 黑龙江省（13个地级市）
        CITY_CODE_MAP.put("哈尔滨", "230100");
        CITY_CODE_MAP.put("哈尔滨市", "230100");
        CITY_CODE_MAP.put("齐齐哈尔", "230200");
        CITY_CODE_MAP.put("鸡西", "230300");
        CITY_CODE_MAP.put("鹤岗", "230400");
        CITY_CODE_MAP.put("双鸭山", "230500");
        CITY_CODE_MAP.put("大庆", "230600");
        CITY_CODE_MAP.put("伊春", "230700");
        CITY_CODE_MAP.put("佳木斯", "230800");
        CITY_CODE_MAP.put("七台河", "230900");
        CITY_CODE_MAP.put("牡丹江", "231000");
        CITY_CODE_MAP.put("黑河", "231100");
        CITY_CODE_MAP.put("绥化", "231200");
        
        // 吉林省（9个地级市）
        CITY_CODE_MAP.put("长春", "220100");
        CITY_CODE_MAP.put("长春市", "220100");
        CITY_CODE_MAP.put("吉林", "220200");
        CITY_CODE_MAP.put("四平", "220300");
        CITY_CODE_MAP.put("辽源", "220400");
        CITY_CODE_MAP.put("通化", "220500");
        CITY_CODE_MAP.put("白山", "220600");
        CITY_CODE_MAP.put("松原", "220700");
        CITY_CODE_MAP.put("白城", "220800");
        
        // 河北省（11个地级市）
        CITY_CODE_MAP.put("石家庄", "130100");
        CITY_CODE_MAP.put("石家庄市", "130100");
        CITY_CODE_MAP.put("唐山", "130200");
        CITY_CODE_MAP.put("秦皇岛", "130300");
        CITY_CODE_MAP.put("邯郸", "130400");
        CITY_CODE_MAP.put("邢台", "130500");
        CITY_CODE_MAP.put("保定", "130600");
        CITY_CODE_MAP.put("张家口", "130700");
        CITY_CODE_MAP.put("承德", "130800");
        CITY_CODE_MAP.put("沧州", "130900");
        CITY_CODE_MAP.put("廊坊", "131000");
        CITY_CODE_MAP.put("衡水", "131100");
        
        // 山西省（11个地级市）
        CITY_CODE_MAP.put("太原", "140100");
        CITY_CODE_MAP.put("太原市", "140100");
        CITY_CODE_MAP.put("大同", "140200");
        CITY_CODE_MAP.put("阳泉", "140300");
        CITY_CODE_MAP.put("长治", "140400");
        CITY_CODE_MAP.put("晋城", "140500");
        CITY_CODE_MAP.put("朔州", "140600");
        CITY_CODE_MAP.put("晋中", "140700");
        CITY_CODE_MAP.put("运城", "140800");
        CITY_CODE_MAP.put("忻州", "140900");
        CITY_CODE_MAP.put("临汾", "141000");
        CITY_CODE_MAP.put("吕梁", "141100");
        
        // 安徽省（16个地级市）
        CITY_CODE_MAP.put("合肥", "340100");
        CITY_CODE_MAP.put("合肥市", "340100");
        CITY_CODE_MAP.put("芜湖", "340200");
        CITY_CODE_MAP.put("蚌埠", "340300");
        CITY_CODE_MAP.put("淮南", "340400");
        CITY_CODE_MAP.put("马鞍山", "340500");
        CITY_CODE_MAP.put("淮北", "340600");
        CITY_CODE_MAP.put("铜陵", "340700");
        CITY_CODE_MAP.put("安庆", "340800");
        CITY_CODE_MAP.put("黄山", "341000");
        CITY_CODE_MAP.put("滁州", "341100");
        CITY_CODE_MAP.put("阜阳", "341200");
        CITY_CODE_MAP.put("宿州", "341300");
        CITY_CODE_MAP.put("六安", "341500");
        CITY_CODE_MAP.put("亳州", "341600");
        CITY_CODE_MAP.put("池州", "341700");
        CITY_CODE_MAP.put("宣城", "341800");
        
        // 江西省（11个地级市）
        CITY_CODE_MAP.put("南昌", "360100");
        CITY_CODE_MAP.put("南昌市", "360100");
        CITY_CODE_MAP.put("景德镇", "360200");
        CITY_CODE_MAP.put("萍乡", "360300");
        CITY_CODE_MAP.put("九江", "360400");
        CITY_CODE_MAP.put("新余", "360500");
        CITY_CODE_MAP.put("鹰潭", "360600");
        CITY_CODE_MAP.put("赣州", "360700");
        CITY_CODE_MAP.put("吉安", "360800");
        CITY_CODE_MAP.put("宜春", "360900");
        CITY_CODE_MAP.put("抚州", "361000");
        CITY_CODE_MAP.put("上饶", "361100");
        
        // 云南省（16个地级市）
        CITY_CODE_MAP.put("昆明", "530100");
        CITY_CODE_MAP.put("昆明市", "530100");
        CITY_CODE_MAP.put("曲靖", "530300");
        CITY_CODE_MAP.put("玉溪", "530400");
        CITY_CODE_MAP.put("保山", "530500");
        CITY_CODE_MAP.put("昭通", "530600");
        CITY_CODE_MAP.put("丽江", "530700");
        CITY_CODE_MAP.put("普洱", "530800");
        CITY_CODE_MAP.put("临沧", "530900");
        
        // 贵州省（9个地级市）
        CITY_CODE_MAP.put("贵阳", "520100");
        CITY_CODE_MAP.put("贵阳市", "520100");
        CITY_CODE_MAP.put("六盘水", "520200");
        CITY_CODE_MAP.put("遵义", "520300");
        CITY_CODE_MAP.put("安顺", "520400");
        CITY_CODE_MAP.put("毕节", "520500");
        CITY_CODE_MAP.put("铜仁", "520600");
        
        // 广西省（14个地级市）
        CITY_CODE_MAP.put("南宁", "450100");
        CITY_CODE_MAP.put("南宁市", "450100");
        CITY_CODE_MAP.put("柳州", "450200");
        CITY_CODE_MAP.put("桂林", "450300");
        CITY_CODE_MAP.put("梧州", "450400");
        CITY_CODE_MAP.put("北海", "450500");
        CITY_CODE_MAP.put("防城港", "450600");
        CITY_CODE_MAP.put("钦州", "450700");
        CITY_CODE_MAP.put("贵港", "450800");
        CITY_CODE_MAP.put("玉林", "450900");
        CITY_CODE_MAP.put("百色", "451000");
        CITY_CODE_MAP.put("贺州", "451100");
        CITY_CODE_MAP.put("河池", "451200");
        CITY_CODE_MAP.put("来宾", "451300");
        CITY_CODE_MAP.put("崇左", "451400");
        
        // 海南省（4个地级市）
        CITY_CODE_MAP.put("海口", "460100");
        CITY_CODE_MAP.put("海口市", "460100");
        CITY_CODE_MAP.put("三亚", "460200");
        CITY_CODE_MAP.put("三亚市", "460200");
        CITY_CODE_MAP.put("三沙", "460300");
        CITY_CODE_MAP.put("儋州", "460400");
        
        // 甘肃省（14个地级市）
        CITY_CODE_MAP.put("兰州", "620100");
        CITY_CODE_MAP.put("兰州市", "620100");
        CITY_CODE_MAP.put("嘉峪关", "620200");
        CITY_CODE_MAP.put("金昌", "620300");
        CITY_CODE_MAP.put("白银", "620400");
        CITY_CODE_MAP.put("天水", "620500");
        CITY_CODE_MAP.put("武威", "620600");
        CITY_CODE_MAP.put("张掖", "620700");
        CITY_CODE_MAP.put("平凉", "620800");
        CITY_CODE_MAP.put("酒泉", "620900");
        CITY_CODE_MAP.put("庆阳", "621000");
        CITY_CODE_MAP.put("定西", "621100");
        CITY_CODE_MAP.put("陇南", "621200");
        
        // 青海省（8个地级市）
        CITY_CODE_MAP.put("西宁", "630100");
        CITY_CODE_MAP.put("西宁市", "630100");
        CITY_CODE_MAP.put("海东", "630200");
        
        // 新疆（自治区）
        CITY_CODE_MAP.put("乌鲁木齐", "650100");
        CITY_CODE_MAP.put("乌鲁木齐市", "650100");
        CITY_CODE_MAP.put("克拉玛依", "650200");
        CITY_CODE_MAP.put("吐鲁番", "650400");
        CITY_CODE_MAP.put("哈密", "650500");
        
        // 西藏（自治区）
        CITY_CODE_MAP.put("拉萨", "540100");
        CITY_CODE_MAP.put("拉萨市", "540100");
        
        // 宁夏（自治区）
        CITY_CODE_MAP.put("银川", "640100");
        CITY_CODE_MAP.put("银川市", "640100");
        CITY_CODE_MAP.put("石嘴山", "640200");
        CITY_CODE_MAP.put("吴忠", "640300");
        CITY_CODE_MAP.put("固原", "640400");
        CITY_CODE_MAP.put("中卫", "640500");
        
        // 内蒙古（自治区）
        CITY_CODE_MAP.put("呼和浩特", "150100");
        CITY_CODE_MAP.put("呼和浩特市", "150100");
        CITY_CODE_MAP.put("包头", "150200");
        CITY_CODE_MAP.put("乌海", "150300");
        CITY_CODE_MAP.put("赤峰", "150400");
        CITY_CODE_MAP.put("通辽", "150500");
        CITY_CODE_MAP.put("鄂尔多斯", "150600");
        CITY_CODE_MAP.put("呼伦贝尔", "150700");
        CITY_CODE_MAP.put("巴彦淖尔", "150800");
        CITY_CODE_MAP.put("乌兰察布", "150900");
        
        log.info("✅ 城市adcode映射已加载，共支持{}个城市", CITY_CODE_MAP.size());
    }
    
    /**
     * 获取实时天气（高德天气API + 缓存）
     */
    public Map<String, Object> getWeather(String city) {
        log.info("获取天气 - 原始城市名: {}", city);
        
        // 处理城市名称
        String processedCity = processCityName(city);
        log.info("获取天气 - 处理后城市名: {}", processedCity);
        
        // 检查缓存
        WeatherCache cache = weatherCacheMap.get(processedCity);
        if (cache != null && !cache.isExpired(cacheMinutes)) {
            log.info("✅ 命中缓存 - 城市: {}, 缓存时间: {}, 有效期: {}分钟", 
                processedCity, cache.getCacheTime(), cacheMinutes);
            Map<String, Object> cachedData = new HashMap<>(cache.getData());
            cachedData.put("fromCache", true);
            cachedData.put("cacheTime", cache.getCacheTime().toString());
            return cachedData;
        }
        
        try {
            // 如果没有配置API key，返回模拟数据
            if (apiKey == null || apiKey.isEmpty() || apiKey.equals("your_weather_api_key")) {
                log.warn("未配置天气API Key，返回模拟数据");
                return getMockWeather(processedCity);
            }
            
            // 获取城市编码
            String cityCode = getCityCode(processedCity);
            if (cityCode == null) {
                log.warn("城市 {} 暂不支持，返回模拟数据", processedCity);
                return getMockWeather(processedCity);
            }
            
            // 调用高德天气API - 实况天气
            String url = String.format("https://restapi.amap.com/v3/weather/weatherInfo?city=%s&key=%s&extensions=base", 
                cityCode, apiKey);
            
            log.info("🌐 调用高德天气API: {}", url.replace(apiKey, "***"));
            
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            JSONObject result = JSON.parseObject(response.getBody());
            
            log.info("高德天气API响应: status={}, info={}", result.getString("status"), result.getString("info"));
            
            // status=1 表示成功
            if ("1".equals(result.getString("status"))) {
                JSONArray lives = result.getJSONArray("lives");
                if (lives != null && lives.size() > 0) {
                    JSONObject live = lives.getJSONObject(0);
                    
                    Map<String, Object> weather = new HashMap<>();
                    weather.put("city", live.getString("city"));
                    weather.put("temp", live.getString("temperature"));
                    weather.put("text", live.getString("weather"));
                    weather.put("windDir", live.getString("winddirection") + "风");
                    weather.put("windPower", live.getString("windpower") + "级");
                    weather.put("humidity", live.getString("humidity"));
                    weather.put("reportTime", live.getString("reporttime"));
                    weather.put("province", live.getString("province"));
                    weather.put("isMock", false);
                    weather.put("fromCache", false);
                    
                    // 存入缓存
                    weatherCacheMap.put(processedCity, new WeatherCache(weather));
                    log.info("✅ 成功获取天气数据并缓存: {}", weather);
                    
                    return weather;
                }
            }
            
            log.warn("获取天气失败: {}, 返回模拟数据", result.getString("info"));
            return getMockWeather(processedCity);
            
        } catch (Exception e) {
            log.error("获取天气异常: {}", e.getMessage(), e);
            return getMockWeather(processedCity);
        }
    }
    
    /**
     * 获取运动建议
     */
    public Map<String, Object> getSportSuggestion(String city, String sportType) {
        Map<String, Object> weather = getWeather(city);
        
        Map<String, Object> suggestion = new HashMap<>();
        suggestion.put("city", city);
        suggestion.put("sportType", sportType);
        
        // 根据天气情况给出运动建议
        String text = (String) weather.get("text");
        int temp = Integer.parseInt((String) weather.getOrDefault("temp", "25"));
        
        String advice;
        String level;
        
        if (text.contains("雨") || text.contains("雪")) {
            advice = "天气不太适合户外运动，建议选择室内场馆";
            level = "不适宜";
        } else if (temp < 0 || temp > 35) {
            advice = "温度较为极端，请注意防护或选择室内运动";
            level = "较不适宜";
        } else if (temp >= 15 && temp <= 28 && text.contains("晴")) {
            advice = "天气非常适合户外运动，快去享受运动的乐趣吧！";
            level = "非常适宜";
        } else {
            advice = "天气适合运动，注意适当补水和休息";
            level = "适宜";
        }
        
        suggestion.put("advice", advice);
        suggestion.put("level", level);
        suggestion.put("temperature", weather.get("temp"));
        suggestion.put("weather", text);
        
        return suggestion;
    }
    
    /**
     * 获取天气预报（高德天气API + 缓存 - 未来3天）
     */
    public Map<String, Object> getWeatherForecast(String city, int days) {
        log.info("获取天气预报 - 城市: {}, 天数: {}", city, days);
        
        String processedCity = processCityName(city);
        String cacheKey = processedCity + "_" + days;
        
        // 检查缓存
        WeatherCache cache = forecastCacheMap.get(cacheKey);
        if (cache != null && !cache.isExpired(cacheMinutes)) {
            log.info("✅ 命中预报缓存 - 城市: {}, 天数: {}, 缓存时间: {}", 
                processedCity, days, cache.getCacheTime());
            Map<String, Object> cachedData = new HashMap<>(cache.getData());
            cachedData.put("fromCache", true);
            cachedData.put("cacheTime", cache.getCacheTime().toString());
            return cachedData;
        }
        
        try {
            if (apiKey == null || apiKey.isEmpty() || apiKey.equals("your_weather_api_key")) {
                return getMockForecast(city, days);
            }
            
            String cityCode = getCityCode(processedCity);
            
            if (cityCode == null) {
                return getMockForecast(city, days);
            }
            
            // 调用高德天气API - 预报天气（extensions=all）
            String url = String.format("https://restapi.amap.com/v3/weather/weatherInfo?city=%s&key=%s&extensions=all", 
                cityCode, apiKey);
            
            log.info("🌐 调用高德天气预报API: {}", url.replace(apiKey, "***"));
            
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            JSONObject result = JSON.parseObject(response.getBody());
            
            if ("1".equals(result.getString("status"))) {
                JSONArray forecasts = result.getJSONArray("forecasts");
                if (forecasts != null && forecasts.size() > 0) {
                    JSONObject forecast = forecasts.getJSONObject(0);
                    JSONArray casts = forecast.getJSONArray("casts");
                    
                    Map<String, Object> forecastData = new HashMap<>();
                    forecastData.put("city", forecast.getString("city"));
                    forecastData.put("province", forecast.getString("province"));
                    forecastData.put("reporttime", forecast.getString("reporttime"));
                    forecastData.put("casts", casts);
                    forecastData.put("isMock", false);
                    forecastData.put("fromCache", false);
                    
                    // 存入缓存
                    forecastCacheMap.put(cacheKey, new WeatherCache(forecastData));
                    log.info("✅ 成功获取天气预报并缓存: {}", forecastData);
                    
                    return forecastData;
                }
            }
            
            return getMockForecast(city, days);
            
        } catch (Exception e) {
            log.error("获取天气预报异常: {}", e.getMessage(), e);
            return getMockForecast(city, days);
        }
    }
    
    /**
     * 获取城市编码
     */
    private String getCityCode(String cityName) {
        return CITY_CODE_MAP.get(cityName);
    }
    
    /**
     * 处理城市名称（去除"市"后缀等）
     */
    private String processCityName(String city) {
        if (city == null || city.isEmpty()) {
            return "北京";
        }
        
        // 去除常见后缀
        city = city.replace("市", "")
                   .replace("省", "")
                   .replace("自治区", "")
                   .replace("特别行政区", "")
                   .trim();
        
        return city;
    }
    
    /**
     * 清理过期缓存
     */
    public void clearExpiredCache() {
        // 清理天气缓存
        weatherCacheMap.entrySet().removeIf(entry -> 
            entry.getValue().isExpired(cacheMinutes));
        
        // 清理预报缓存
        forecastCacheMap.entrySet().removeIf(entry -> 
            entry.getValue().isExpired(cacheMinutes));
        
        log.info("已清理过期缓存");
    }
    
    /**
     * 清理所有缓存
     */
    public void clearAllCache() {
        weatherCacheMap.clear();
        forecastCacheMap.clear();
        log.info("已清空所有缓存");
    }
    
    /**
     * 获取缓存统计信息
     */
    public Map<String, Object> getCacheStats() {
        Map<String, Object> stats = new HashMap<>();
        stats.put("weatherCacheSize", weatherCacheMap.size());
        stats.put("forecastCacheSize", forecastCacheMap.size());
        stats.put("cacheMinutes", cacheMinutes);
        stats.put("totalCacheSize", weatherCacheMap.size() + forecastCacheMap.size());
        return stats;
    }
    
    /**
     * 模拟天气数据（用于演示或API调用失败时）
     */
    private Map<String, Object> getMockWeather(String city) {
        Map<String, Object> weather = new HashMap<>();
        weather.put("city", city);
        weather.put("temp", "25");
        weather.put("text", "晴");
        weather.put("windDir", "东南风");
        weather.put("windPower", "3级");
        weather.put("humidity", "45");
        weather.put("reportTime", "2025-10-28 12:00:00");
        weather.put("isMock", true);
        return weather;
    }
    
    /**
     * 模拟天气预报数据
     */
    private Map<String, Object> getMockForecast(String city, int days) {
        Map<String, Object> forecast = new HashMap<>();
        forecast.put("city", city);
        forecast.put("reporttime", "2025-10-28 12:00:00");
        
        JSONArray casts = new JSONArray();
        for (int i = 0; i < days; i++) {
            JSONObject cast = new JSONObject();
            cast.put("date", "2025-10-" + (28 + i));
            cast.put("week", String.valueOf(i + 1));
            cast.put("dayweather", "晴");
            cast.put("nightweather", "晴");
            cast.put("daytemp", "28");
            cast.put("nighttemp", "18");
            cast.put("daywind", "东南");
            cast.put("nightwind", "东南");
            cast.put("daypower", "3");
            cast.put("nightpower", "3");
            casts.add(cast);
        }
        
        forecast.put("casts", casts);
        forecast.put("isMock", true);
        return forecast;
    }
}
